package export;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * ExportFileDownloader is only used in client server export to download export file from server to client after export
 * success.
 * 
 */
public class ExportFileWriter {
    private static final int KB_SIZE = 8192;

    /**
     * Write file from input stream response at server side.
     * 
     * @param fileStream
     *            InputStream return by server side.
     * @param localPath
     *            Local path is used to save file.
     * @return Local path.
     * @throws IOException
     *             throw if having any problem in writing file process.
     */
    public String downloadExportFile(InputStream fileStream, String localPath) throws IOException {
        BufferedOutputStream exportFile = null;
        BufferedInputStream inputStream = null;
        try {
            inputStream = new BufferedInputStream(fileStream);

            // write data from server response to array
            // read 1kb at a time
            byte[] data = new byte[KB_SIZE];

            File file = new File(localPath);

            if (file.getParentFile() != null && !file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            // open downloaded file
            exportFile = new BufferedOutputStream(new FileOutputStream(file, false));

            int count;
            // write to file, this loop for make sure all data will be transfered from server side to client side.
            while ((count = inputStream.read(data)) != -1) {
                exportFile.write(data, 0, count);
            }

            // flush to make sure all data was written into file.
            exportFile.flush();

        } finally {
            if (exportFile != null) {
                exportFile.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return localPath;
    }
}
